package com.resifind.www.dao.impl;

import com.resifind.www.dao.MerchantDao;
import com.resifind.www.dao.mapper.Mappers;
import com.resifind.www.po.*;
import com.resifind.www.util.JdbcUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 36069
 */
public class MerchantDaoImpl implements MerchantDao {

    @Override
    public boolean addMerchant(int userId, Connection conn) {
        //language=MySQL
        String sql = "insert into resi_find.merchant (user_id) values (?)";
        Object[] params = new Object[]{userId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public Merchant queryMerchantByMerchantId(int merchantId) {
        //language=MySQL
        String sql = "select *, 0 as is_favour from resi_find.merchant where id = ?";
        Object[] params = new Object[]{merchantId};
        List<Merchant> merchantList = Mappers.merchantMapper(sql, params);
        return merchantList.isEmpty() ? null : merchantList.getFirst();
    }

    @Override
    public List<Merchant> queryOpenMerchantForClient(int currentPage, int pageSize, String tradeName, int clientId) {
        //language=MySQL
        String sql = """
                select m.*, if(f.merchant_id is null, 0, 1) as is_favour
                from resi_find.merchant m
                left join resi_find.favour f on m.id = f.merchant_id and f.client_id = ?
                where m.business_status = '正常营业' and m.application_status = '已通过'
                and not exists (select 1 from resi_find.blacklist b
                    where b.merchant_id = m.id and b.client_id = ?)
                """;
        List<Object> params = new ArrayList<>();
        params.add(clientId);
        params.add(clientId);
        //添加分页和条件查询
        sql = addPageAndCondition(currentPage, pageSize, tradeName, sql, params);
        return Mappers.merchantMapper(sql, params.toArray());
    }

    @Override
    public List<Merchant> queryOpenMerchantForGuest(int currentPage, int pageSize, String tradeName) {
        //language=MySQL
        String sql = """
                select m.*, 0 as is_favour from resi_find.merchant m
                where m.business_status = '正常营业' and m.application_status = '已通过'
                """;
        List<Object> params = new ArrayList<>();
        sql = addPageAndCondition(currentPage, pageSize, tradeName, sql, params);
        return Mappers.merchantMapper(sql, params.toArray());
    }

    @Override
    public List<Merchant> queryAllMerchantForAdmin(int currentPage, int pageSize, String tradeName) {
        //language=MySQL
        String sql = """
                select m.*, 0 as is_favour from resi_find.merchant m
                where true
                """;
        List<Object> params = new ArrayList<>();
        sql = addPageAndCondition(currentPage, pageSize, tradeName, sql, params);
        return Mappers.merchantMapper(sql, params.toArray());
    }

    @Override
    public int queryMerchantCountForClient(String tradeName, int clientId) {
        //language=MySQL
        String sql = """
                select count(*) from resi_find.merchant m
                where m.business_status = '正常营业' and m.application_status = '已通过'
                and not exists (select 1 from resi_find.blacklist b
                    where b.merchant_id = m.id and b.client_id =?)
                """;
        List<Object> params = new ArrayList<>();
        params.add(clientId);
        List<Integer> query = JdbcUtils.query(sql, params.toArray(), rs -> rs.getInt(1));
        return query.getFirst();
    }

    @Override
    public int queryMerchantCountForGuest(String tradeName) {
        //language=MySQL
        String sql = """
                select count(*) from resi_find.merchant m
                where m.business_status = '正常营业' and m.application_status = '已通过'
                """;
        List<Object> params = new ArrayList<>();
        sql = addCondition(tradeName, sql, params);
        List<Integer> query = JdbcUtils.query(sql, params.toArray(), rs -> rs.getInt(1));
        return query.getFirst();
    }

    @Override
    public int queryMerchantCountForAdmin(String tradeName) {
        //language=MySQL
        String sql = """
                select count(*) from resi_find.merchant m
                where true
                """;
        List<Object> params = new ArrayList<>();
        sql = addCondition(tradeName, sql, params);
        List<Integer> query = JdbcUtils.query(sql, params.toArray(), rs -> rs.getInt(1));
        return query.getFirst();
    }

    /**
     * sql添加条件查询
     */
    private static String addCondition(String tradeName, String sql, List<Object> params) {
        if (tradeName != null && !tradeName.isEmpty()) {
            // 按照商家店名模糊查询
            sql += "and m.trade_name like ? ";
            params.add("%" + tradeName + "%");
        }
        return sql;
    }

    /**
     * sql添加分页和条件查询
     */
    private static String addPageAndCondition(int currentPage, int pageSize, String tradeName, String sql, List<Object> params) {
        sql = addCondition(tradeName, sql, params);
        //分页条件
        sql += "limit ?, ? ";
        params.add((currentPage - 1) * pageSize);
        params.add(pageSize);
        return sql;
    }

    @Override
    public Merchant queryMerchantByUserId(int userId) {
        //language=MySQL
        String sql = "select *, 0 as is_favour from resi_find.merchant where user_id = ?";
        Object[] params = {userId};
        // 执行查询并映射结果到Merchant对象
        List<Merchant> merchantList = Mappers.merchantMapper(sql, params);
        if (merchantList.isEmpty()) {
            return null;
        } else {
            return merchantList.getFirst();
        }
    }

    @Override
    public Merchant queryMerchantByRoomId(int roomId) {
        //language=MySQL
        String sql = "select m.*, 0 as is_favour from resi_find.merchant m join resi_find.room r on m.id = r.merchant_id where r.id = ?";
        Object[] params = {roomId};
        // 执行查询并映射结果到Merchant对象
        List<Merchant> merchantList = Mappers.merchantMapper(sql, params);
        if (merchantList.isEmpty()) {
            return null;
        } else {
            return merchantList.getFirst();
        }
    }

    @Override
    public boolean update(Merchant merchant, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.merchant set trade_name = ?, address = ?, contact = ?, keyword = ?, business_status = ? where id = ?";
        Object[] params = {merchant.getTradeName(), merchant.getAddress(), merchant.getContact(), merchant.getKeyword(), merchant.getBusinessStatus(), merchant.getId()};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public List<Merchant> queryPendingMerchants() {
        //language=MySQL
        String sql = "select *, 0 as is_favour from resi_find.merchant where application_status = '申请中'";
        Object[] params = {};
        return Mappers.merchantMapper(sql, params);
    }

    @Override
    public boolean updateMerchantStatus(int merchantId, String newStatus, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.merchant set application_status = ? where id = ?";
        Object[] params = {newStatus, merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean updateTotalSales(int merchantId, int num, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.merchant set total_sales = total_sales + ? where id = ?";
        Object[] params = {num, merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean updateTurnover(int merchantId, double amount, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.merchant set turnover = turnover + ? where id = ?";
        Object[] params = {amount, merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

    @Override
    public boolean updateViewCount(int merchantId, Connection conn) {
        //language=MySQL
        String sql = "update resi_find.merchant set view = view + 1 where id = ?";
        Object[] params = {merchantId};
        return JdbcUtils.update(sql, params, conn);
    }

}
